package airport.user.action;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import airport.user.pojo.User;
import airport.user.dao.UserDAO;
import airport.pk.validate.ValidateLibrary;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class UploadImageAction extends ActionSupport implements
		ServletRequestAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File userImage;
	private String userImageContentType;
	private String userImageFileName;
	private String username;
	private String path;
	//private String type;

	private HttpServletRequest servletRequest;

	public String execute() {
		/**
		 * get the path of the uploaded file
		 */
		path = username+"\\\\" + this.userImageFileName;
		System.out.println("My Path:"+path);
		UserDAO dao = new UserDAO();
		User user = dao.findUserByUserName(username);
		if ((user.getAvatar()!=null)&&!(user.getAvatar().equals(path)))
		{
			//delete the old file
			System.out.println("avatar:"+user.getAvatar());
			@SuppressWarnings("deprecation")
			String p = servletRequest.getRealPath("/");
			p = p + user.getAvatar();
			System.out.println("p:" + p);
			File file = new File(p);
			try {
				DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
				if (file.isFile()&&file.exists()){
					System.out.println("File existing!!!!");
					System.out.println("delete file!");
					file.delete();
				}
				dos.close();
			}
			catch (Exception e){
				e.printStackTrace();
			}
		}
		dao.updateAvatar(path, username);
		return SUCCESS;
	}
	
	public void validate() {
		/**
		 * check if the upload file is validate format, and the filename + user name should not be larger than 255, which is specified in the DB
		 */
		//get the user name from cookie
		Cookie[] cookies = servletRequest.getCookies();
		String cookieName = "AirportUser";
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(cookieName)) {
					username = cookies[i].getValue();
					break;
				}
			}
		}
		System.out.println("validate username:"+username);
		File fileToCreate = null;
		//boolean flag = false;
		int length = 0;
		length = username.length() + 1 + userImageFileName.length();
		if (length > 255) {
			addFieldError("userImage","File Name is too long");
		}
		else {
			//check the type of the file
			try {
				@SuppressWarnings("deprecation")
				String filePath = servletRequest.getRealPath("/");
				System.out.println("System Path:" + filePath);
				filePath = filePath+username+"\\";
				System.out.println("before file to create");
				fileToCreate = new File(filePath, this.userImageFileName);
				FileUtils.copyFile(this.userImage, fileToCreate);
				long fileLength = fileToCreate.length();
				System.out.print("The length of the file:");
				System.out.println(fileLength);
				if (fileLength > 200000) {
					System.out.println("the length exceed 200");
					addFieldError("userImage","File Length should be no more than 200 KB!");
				}
				else {
					FileInputStream is = new FileInputStream (fileToCreate);
					String type = ValidateLibrary.getTypeByStream(is);
					System.out.println("type="+type);
					if (type.length() > 3) {
						addFieldError("userImage","Invalid File Type!");
						System.out.println("This is an invalid File!");
					}	
				}
			}
			catch (Exception e){
				e.printStackTrace();
				addFieldError("userImage", "Invalid File!");
			}
		}
		if (fileToCreate!=null)
			fileToCreate.delete();
		
	}

	public File getUserImage() {
		return userImage;
	}

	public void setUserImage(File userImage) {
		this.userImage = userImage;
	}

	public String getUserImageContentType() {
		return userImageContentType;
	}

	public void setUserImageContentType(String userImageContentType) {
		this.userImageContentType = userImageContentType;
	}

	public String getUserImageFileName() {
		return userImageFileName;
	}

	public void setUserImageFileName(String userImageFileName) {
		this.userImageFileName = userImageFileName;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
}
